import React, { useState } from 'react'
import { useNavigate } from 'react-router-dom'
import axios from 'axios'
// 引入进度条
import nprogress from 'nprogress'
// 引入进度条样式
import 'nprogress/nprogress.css'
import { useDispatch } from 'react-redux'
import { clearData } from '../store/reducers/tab'
import { message } from 'antd'
import { storage } from '../utils'
const baseUrl = ''

const request = axios.create({
  baseURL: baseUrl,
  timeout: 5000
})

const { getItem, clear } = storage

const useRequest = () => {
  // 跳转路由
  const navigate = useNavigate()

  //创建dispatch
  const dispatch = useDispatch()

  request.interceptors.request.use(config => {
    nprogress.start()
    const token = getItem('token')
    if (token) {
      config.headers['authorization'] = token
    }

    return config
  })

  request.interceptors.response.use(
    res => {
      nprogress.done()
      //token过期
      if (res?.code == 401) {
        //清除所有缓存
        clear()
        dispatch(clearData())
        navigate('/login')
        message.warning({
          content: '登录过期，请重新登录',
          duration: 2,
          maxCount: 1
        })
        return
      }

      //权限不够，不同用户登录
      if (res?.code == 402) {
        //清除所有缓存
        clear()
        dispatch(clearData())
        navigate('/login')
        message.warning({
          content: '用户权限异常，请重新登录',
          duration: 2,
          maxCount: 1
        })
        return
      }

      return res?.data ?? res
    },
    err => {
      //中断请求，err.message == 'canceled'
      if (err.message !== 'canceled') {
        console.log('err', err)
        message.error('网络异常')
      }

      nprogress.done()
      return Promise.reject(new Error(err))
    }
  )

  return request
}

export default useRequest
